<template>
	<view>
		<TopNav title="销售记录"></TopNav>
		<u-form class="padding-lr-sm padding-bottom" labelWidth="88px" :model="form" ref="form" :rules="rules">
			<view class="padding-tb">
				<text class="cuIcon-title text-gray"></text>
				<text class="">基本信息</text>
			</view>
			<view class="padding-tb-xs padding-lr radius bg-white">
				<u-form-item label="时间" borderBottom required @click="handleOpenDateSelect" prop="time">
					<u-input :value="form.time" border="none" inputAlign="right" placeholder="选择记录时间"
						class="pointer-none">
						<u-icon slot="suffix" name="arrow-right"></u-icon>
					</u-input>
				</u-form-item>
				<u-form-item label="销售人" borderBottom required prop="salePersonnel">
					<u-input v-model="form.salePersonnel" border="none" placeholder="填写销售人"
						inputAlign="right"></u-input>
				</u-form-item>
				<u-form-item label="销售产品" borderBottom required prop="categoryList" @click="handleOpenProductsSelect">
					<u-input :value="`${form.categoryList.length?'已选'+form.categoryList.length+'个产品':''}`" border="none"
						inputAlign="right" placeholder="选择销售产品" readonly class="pointer-none">
						<u-icon slot="suffix" name="arrow-right"></u-icon>
					</u-input>
				</u-form-item>
				<u-form-item label="销售总价" required prop="totalPrice">
					<u-input v-model="form.totalPrice" border="none" placeholder="填写销售总价" inputAlign="right">
						<view slot="suffix">
							<text>元</text>
						</view>
					</u-input>
				</u-form-item>
			</view>
			<view class="" v-if="form.categoryList.length">
				<view class="padding-tb">
					<text class="cuIcon-title text-blue"></text>
					<text class="">已选销售产品</text>
				</view>
				<view class="padding-tb-xs padding-lr radius bg-white" v-for="(item,index) in form.categoryList"
					:key="index">
					<view class="padding-tb-xs flex justify-between align-center">
						<view class="text-cut text-black text-bold">
							<text>{{index+1}}.</text>
							<text>{{item.aquaticName}}</text>
						</view>
						<view @click.stop>
							<uni-icons type="trash" size="18" color="#e54d42"
								@click="handleRemoveProducts(index)"></uni-icons>
						</view>
					</view>
					<u-form-item label="销售数量" required prop="quantity">
						<u-input v-model.number="item.quantity" border="none" placeholder="填写销售数量" inputAlign="right">
							<view slot="suffix">
								<text>{{item.quantityUnitDictName}}</text>
							</view>

						</u-input>
					</u-form-item>
					<u-form-item label="销售价格" borderBottom required prop="totalPrice">
						<u-input v-model="item.price" border="none" placeholder="填写销售价格" inputAlign="right">
							<view slot="suffix">
								<text>元</text>
							</view>
						</u-input>
					</u-form-item>
				</view>
			</view>
			<view class="padding-tb">
				<text class="cuIcon-title text-gray"></text>
				<text class="">收购信息</text>
			</view>
			<view class="padding-tb-xs padding-lr radius bg-white">
				<u-form-item label="收购方" borderBottom required prop="acquirer">
					<u-input v-model="form.acquirer" border="none" placeholder="填写收购方" inputAlign="right"></u-input>
				</u-form-item>
				<u-form-item label="联系电话" borderBottom required prop="acquirerPhoneNumber">
					<u-input v-model.number="form.acquirerPhoneNumber" border="none" placeholder="填写联系电话"
						inputAlign="right"></u-input>
				</u-form-item>
				<u-form-item label="地址" labelPosition="top" prop="acquirerAddress">
					<u-textarea v-model="form.acquirerAddress" border="bottom" placeholder="填写收购方地址"
						autoHeight></u-textarea>
				</u-form-item>
				<u-form-item label="送货方式" borderBottom prop="deliveryMethodDict">
					<DictPicker dict="biz_sale_record_delivery_method" v-model="form.deliveryMethodDict"
						placeholder="选择送货方式" :first="false">
					</DictPicker>
				</u-form-item>
				<u-form-item label="送货费用" prop="deliveryCost">
					<u-input v-model.number="form.deliveryCost" border="none" placeholder="填写送货费用" inputAlign="right">
						<view slot="suffix">
							<text>元</text>
						</view>
					</u-input>
				</u-form-item>
			</view>
			<view class="padding-tb-xs padding-lr radius bg-white margin-top">
				<u-form-item label="备注" labelPosition="top">
					<u-textarea v-model="form.remarks" border="bottom" placeholder="填写备注信息" autoHeight
						></u-textarea>
				</u-form-item>

			</view>
			<view class="padding-tb">
				<text class="cuIcon-title text-gray"></text>
				<text class="">相关图片</text>
			</view>
			<view class="padding radius bg-white">
				<UploadImage v-model="form.fileUrls" :limit="9" ></UploadImage>
			</view>
		</u-form>
		<view class="bottom-tools padding flex justify-around bg-white">
			<van-button class='basis-xl' type="info" @click="handleSubmit">
				提交
			</van-button>
		</view>
		<u-datetime-picker :show="dateShow" :value="timestampFormat" mode="datetime" closeOnClickOverlay
			:maxDate="maxDate" :minDate="minDate" @close="handleCloseDateSelect" @cancel="handleCloseDateSelect"
			@confirm="handleConfirmDateSelect"></u-datetime-picker>

	</view>
</template>

<script>
	import UploadImage from "@/components/upload-image.vue"
	import dayjs from 'dayjs'
	import {
		monitoringFactors,
		detail,
		add,
		update
	} from "@/api/work/sale"
	import DictPicker from '@/components/dict-picker/index.vue'

	export default {
		components: {
			UploadImage,
			DictPicker
		},
		data() {
			return {
				maxDate: dayjs().valueOf(),
				minDate: dayjs('2024-01-01 00:00').valueOf(),
				dateShow: false,
				queryParams: {
					id: undefined
				},
				form: {
					productionBaseId: undefined,
					time: dayjs().format('YYYY-MM-DD HH:mm'),
					saleCategory: undefined,
					quantity: undefined,
					quantityUnitDict: undefined,
					totalPrice: undefined,
					salePersonnel: undefined,
					acquirer: undefined,
					acquirerPhoneNumber: undefined,
					acquirerAddress: undefined,
					deliveryMethodDict: undefined,
					deliveryCost: undefined,
					categoryList: [],
					remarks: undefined,
					fileUrls: undefined
				},
				rules: {
					categoryList: {
						type: 'array',
						min: 1,
						required: true,
						message: '请选择销售产品',
						trigger: ['blur', 'change']
					},
					time: {
						type: 'string',
						required: true,
						message: '记录时间不能为空',
						trigger: ['blur', 'change']
					},
					totalPrice: {
						type: 'number',
						required: true,
						message: '销售总价不能为空',
						trigger: ['blur', 'change']
					},
					salePersonnel: {
						type: 'string',
						required: true,
						message: '销售人不能为空',
						trigger: ['blur', 'change']
					},
					acquirer: {
						type: 'string',
						required: true,
						message: '收购方不能为空',
						trigger: ['blur', 'change']
					},
					acquirerPhoneNumber: {
						type: 'number',
						required: true,
						message: '收购方电话不能为空',
						trigger: ['blur', 'change']
					}

				}

			}
		},
		computed: {
			timestampFormat() {
				return dayjs(this.form.time).valueOf()
			}
		},
		watch: {
			"form.categoryList": {
				deep: true,
				handler(list) {
					let totalPrice = list.reduce((prev, curr) => {
						return prev + Number(curr.price);
					}, 0);
					this.$set(this.form, "totalPrice", totalPrice);
				},
			}
		},
		onReady() {
			//onReady 为uni-app支持的生命周期之一
			this.$refs.form.setRules(this.rules)
			setTimeout(() => {
				this.$refs.form.clearValidate('quantity')
			}, 1000)
		},
		onLoad(query) {
			this.form.productionBaseId = this.$store.state.user.baseInfo.id
			if (query.id) {
				this.queryParams.id = query.id
				this.getDetail()
			}
		},
		onShow() {

		},
		methods: {
			handleRemoveProducts(index) {
				this.form.categoryList.splice(index, 1)
			},
			receiveProductsSelect(selection) {
				if (!selection.length) return;
				/** 判断categoryList是否已有数据，无则直接填充选择数据 */
				if (this.form.categoryList.length !== 0) {
					/** 新选择数据与原数据对比，交集数据不修改，并集数据填充 */
					selection.forEach((element) => {
						let find = this.form.categoryList.find(
							(item) => element.id == item.aquaticId
						);
						if (!find) {
							this.form.categoryList.push({
								id: element.id,
								aquaticId: element.id,
								aquaticName: element.name,
								quantity: 0,
								quantityUnitDict: element.specificationsUnitDict,
								quantityUnitDictName: element.specificationsUnitDictName,
								price: 0,
							});
						}
					});
					/** 判断最新选择数据是否取消产品选中 */
					this.form.categoryList.forEach((ele, index) => {
						let findIndex = selection.findIndex(
							(item) => ele.aquaticId == item.id
						);
						/** 未匹配到选择数据则删除该数据 */
						if (findIndex === -1) {
							this.form.categoryList.splice(index, 1);
						}
					});
				} else {
					this.form.categoryList = selection.map((item) => {
						return {
							id: item.id,
							aquaticId: item.id,
							aquaticName: item.name,
							quantity: 0,
							quantityUnitDict: item.specificationsUnitDict,
							quantityUnitDictName: item.specificationsUnitDictName,
							price: 0,
						};
					});
				}
				console.log('this.form.categoryList: ', this.form.categoryList);
			},
			handleOpenProductsSelect() {
				uni.$on('productsSelect', this.receiveProductsSelect)
				let ids = this.form.categoryList.map(item => item.aquaticId).join(",")
				this.$tab.navigateTo('/pages/work/catch-inventory/select?multiple=true&id=' + ids)
			},
			handleSubmit() {
				this.$refs.form.validate().then(res => {
					add(this.form).then(res => {
						this.$tab.navigateBack()
					})
				})
			},
			getDetail() {
				detail(this.queryParams).then(res => {
					this.form = res.data
					this.specifications = res.data.feedstuffSpecifications
					this.specificationsUnitDictName = res.data.feedstuffSpecificationsUnitDictName
				})
			},

			handleCloseDateSelect() {
				this.dateShow = false
			},
			handleConfirmDateSelect(date) {
				this.form.time = dayjs(date.value).format('YYYY-MM-DD HH:mm')
				this.dateShow = false
			},
			handleOpenDateSelect() {
				this.dateShow = true
			},
			reset() {
				this.form = {
					productionBaseId: undefined,
					time: dayjs().format('YYYY-MM-DD HH:mm'),
					saleCategory: undefined,
					quantity: undefined,
					quantityUnitDict: undefined,
					totalPrice: undefined,
					salePersonnel: undefined,
					acquirer: undefined,
					acquirerPhoneNumber: undefined,
					acquirerAddress: undefined,
					deliveryMethodDict: undefined,
					deliveryCost: undefined,
					remarks: undefined,
					fileUrls: undefined
				}
				this.$nextTick(() => {
					this.$refs.form.resetFields()
				})
			}
		}
	}
</script>

<style lang="scss">
	@import "@/common/var.scss";
	page {
		@include fixed-bottom;
	}

</style>
